<template>
    <section class="content">
        <Panel :expandable="false" :expand="true">
            <template slot="title">商品对应关系查询</template>
            <template slot="body">
                <el-form label-width="80px">
                    <el-row :gutter="20">
                        <el-col :span="10">
                            <el-input v-model="searchValue" class="input-with-select">
                                <el-select v-model="type" slot="prepend" placeholder="请选择" style="width:110px">
                                    <el-option v-for="t in types" :label="t.text" :value="t.value" :key="t.value"></el-option>
                                </el-select>
                            </el-input>
                        </el-col>
                        <el-col :span="12">
                            <el-button type="success" @click="handleSearch">搜索</el-button>
                            <el-button type="primary" style="margin-left: 20px" @click="handleAdd">新增</el-button>
                            <el-dropdown placement="bottom-start" trigger="click" split-button type="primary" style="margin-left: 20px" @command="handleExport">
                                导入
                                <el-dropdown-menu slot="dropdown">
                                    <el-dropdown-item command="1">导入</el-dropdown-item>
                                    <el-dropdown-item command="2">导入模板下载</el-dropdown-item>
                                </el-dropdown-menu>
                            </el-dropdown>
                            <el-upload style="display: none"
                                ref="upload"
                                class="upload-demo"
                                :action="uploadUrl"
                                name="fileName"
                                :on-success="handleSuccess"
                                :on-error="handleError"
                                :show-file-list="false"
                                :headers = "headers"
                                :before-upload="beforeUpload"
                                >
                                <el-button type="primary">导入</el-button>
                            </el-upload>
                            <!-- <el-button type="primary" @click="handleDownloadTemplate">导入模板下载</el-button> -->
                        </el-col>
                    </el-row>
                </el-form>
            </template>
        </Panel>

        <Panel :expandable="false" :expand="true" :hasTitle="false">
            <template slot="title"></template>
            <template slot="body">
                <el-table :data="list" header-row-class-name="header-class">
                    <el-table-column prop="channelStr" label="平台" align="center"></el-table-column>
                    <el-table-column prop="sku" label="平台SKU" align="center"></el-table-column>
                    <el-table-column prop="erpSku" label="系统SKU" align="center"></el-table-column>
                    <el-table-column prop="gmtModified" label="时间" align="center"></el-table-column>
                    <el-table-column prop="modifier" label="新增/修改" align="center"></el-table-column>
                    <el-table-column label="操作" align="center">
                        <template slot-scope="scope">
                            <i class="iconfont rticon-bianji" style="color: #409EFF; font-size: 20px" @click="handleEdit(scope.row)"/>
                            <i style="margin-left: 23px; color: #409EFF; font-size: 20px" class="iconfont rticon-shanchu" @click="handleDelete(scope.row)"/>
                        </template>
                    </el-table-column>
                </el-table>

                <div class="clear-fix">
                    <el-pagination
                        style="float: right; margin-top: 20px;"
                        background
                        layout="total, prev, pager, next"
                        @current-change="handleCurrentChange"
                        @prev-click="handlePrev"
                        @next-click="handleNext"
                        :current-page.sync="searchParam.page"
                        :total="searchParam.total">
                    </el-pagination>
                </div>
            </template>
        </Panel>

        <el-dialog :visible.sync="visible" class="add-dialog" width="530px" :title="commodityTitle">
            <el-form ref="form" :rules="rules" :model="this.form">
                <hr/>
                <el-form-item label="平台：" prop="channel" label-width="82px">
                    <el-select v-model="form.channel" style="width: 400px">
                        <el-option v-for="p in platforms" :label="p.platformName" :value="p.id" :key="p.id"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="平台SKU：" prop="sku" label-width="82px">
                    <el-input v-model="form.sku" style="width: 400px"></el-input>
                </el-form-item>
                <el-form-item label="系统SKU：" prop="erpSku" label-width="82px">
                    <el-select v-model="form.erpSku" style="width: 400px" filterable placeholder="请选择">
                        <el-option
                            v-for="item in skus"
                            :key="item.value"
                            :label="item.value"
                            :value="item.value">
                        </el-option>
                    </el-select>
                </el-form-item>
            </el-form>
             <span slot="footer" class="dialog-footer">
                <el-button type="primary" @click="handleSave">保存</el-button>
                <el-button @click="visible = false">关闭</el-button>
            </span>
        </el-dialog>

        <el-dialog :visible.sync="errorVisible" title="提示">
            <el-table :data="errorList">
                <el-table-column label="以下商品对应关系未导入，请检查" align="center">
                    <el-table-column width="50" type="index" label="序号"></el-table-column>
                    <el-table-column prop="channelStr" label="平台" align="center"></el-table-column>
                    <el-table-column prop="sku" label="平台SKU" align="center"></el-table-column>
                    <el-table-column prop="erpSku" label="系统SKU" align="center"></el-table-column>
                    <el-table-column prop="errorMsg" label="异常原因" align="center"></el-table-column>
                </el-table-column>
            </el-table>
            <div class="clear-fix">
                <el-pagination
                style="float: right; margin-top: 20px;"
                background
                layout="total,prev, pager, next"
                :total="errorTotal"
                :pager-count="6"
                :current-page="errorPage"
                @current-change="handleErrorCurrentChange"
                />
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button @click="errorVisible = false">关闭</el-button>
            </span>
        </el-dialog>
    </section>
</template>
<script>
import instance from '@/api/index.js'
import Panel from '@/components/common/panel'
import baseURL from '@/js/common/baseURL'
import { getCookie } from "@/js/common/util"
import ClientPagination from '@/js/common/ClientPagination'

function required(rule, value, callback) {
    if(value == null || value =='') {
        callback(new Error('必填'));
    }
    let v = value.trim();
    if(v == '') {
        callback(new Error('必填'));
    }

    callback();
}

export default {
    name: "productRelation",
    data() {
        let token = getCookie('token');
        return {
            uploadUrl: baseURL + "/v1/goodsRelation/import",
            commodityTitle: "新增商品对应关系",
            searchParam: {
                page: 1,
                rows: 10,
                total: 0
            },
            searchValue: "",
            visible: false,
            form: {
                sku: "",
                erpSku: "",
                channel: ""
            },
            list: [],
            platforms: [],
            skus: [],
            rules: {
                channel: [{ required: true, message: '必填', trigger: 'change' }],
                sku: [{validator: required, message: "必填", trigger: 'blur'}, {required: true, message: "必填"}],
                erpSku: [{validator: required, message: "必填", trigger: 'change'}, {required: true, message: "必填"}]
            },
            headers: {
                Authorization: token
            },
            types: [{
                text: "平台sku",
                value: 1,
            }, {
                text: "系统sku",
                value: 2
            }],
            type: 1,
            errorVisible: false,
            errorList: [],
            errorTotal: 0,
            errorPage: 1,
        };
    },
    components: {
        Panel
    },
    created() {
        // this.getList();
        this.getPlatform();
        this.getAllSku();
        this.clientPagination = new ClientPagination();
        this.clientPagination.search(function(){return true;});
    },
    methods: {
        // 搜索
        handleSearch() {
            this.searchParam.page = 1;
            this.getList();
        },
        // 新增
        handleAdd() {
            this.commodityTitle = "新增商品对应关系";
            this.visible = true;
            this.form = {
                sku: "",
                erpSku: "",
                channel: ""
            };
            this.$nextTick(()=>{
                if(this.$refs.form)
                    this.$refs.form.clearValidate();
            })
        },
        // 下载模板
        handleDownloadTemplate() {
            let url = baseURL+'/v1/goodsRelation/download';
            let link = document.createElement('a');
            link.style.display = 'none';
            link.href = url;
            link.setAttribute('download', '报关单模板');
            document.body.appendChild(link);
            link.click();
        },
        handleDelete(item) {
            let self = this;
            this.$confirm('确定删除?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                instance({
                    method: 'delete',
                    url: '/v1/goodsRelation/delete/' + item.id,
                }).then(function (data) {
                    if(data.data.success){
                        self.$message.success("操作成功！");
                        self.getList();
                    }
                }).catch(function (err) {

                });
            }).catch(() => {

            });
        },
        // 编辑
        handleEdit(item) {
            this.commodityTitle = "编辑商品对应关系";
            console.log(item);
            let form = {
                id: item.id,
                sku: item.sku,
                erpSku: item.erpSku,
                channel: item.channel
            };
            this.form = form;
            this.visible = true;
            if(this.$refs.form)
                this.$refs.form.clearValidate();
        },

        getList() {
            let self = this;
            let param = {
                page: this.searchParam.page,
                rows: this.searchParam.rows,
            };
            // 平台sku
            if(this.type == 1) {
                param.sku = this.searchValue;
            }
            // 系统sku
            if(this.type == 2) {
                param.erpSku = this.searchValue;
            }

            instance({
                method: 'get',
                url: '/v1/goodsRelation/list',
                params: param
            }).then(function (data) {
                console.log(data);
                if(data.data.success){
                    // 1: ebay 2:amazon , 3 : magento
                    // let channels = ['', 'ebay', 'amazon', 'magento'];
                    let channels = {};
                    self.platforms.forEach(p=>{
                        channels[p.id] = p.platformName;
                    });
                    self.list = data.data.data.list.map(d=>{
                        d.channelStr = channels[d.channel] || '';
                        return d;
                    });
                    self.searchParam.total = data.data.data.total;
                }
            }).catch(function (err) {

            });
        },

        handleCurrentChange(pageIndex) {
            this.searchParam.page = pageIndex;
            this.getList();
        },
        handleNext(pageIndex) {
            this.searchParam.page = pageIndex;
            this.getList();
        },
        handlePrev(pageIndex) {
            this.searchParam.page = pageIndex;
            this.getList();
        },

        handleSave() {
            let self = this;
            // let param = this.form;
            this.$refs.form.validate(valid=>{
                if(valid) {
                    let param = {
                        id: self.form.id,
                        sku: self.form.sku.trim(),
                        erpSku: self.form.erpSku.trim(),
                        channel: self.form.channel
                    };
                    instance({
                        method: 'post',
                        url: '/v1/goodsRelation/save',
                        data: param
                    }).then(function (data) {
                        if(data.data.success){
                            self.$message.success("操作成功！");
                            self.visible = false;
                            self.getList();
                        }
                    }).catch(function (err) {

                    });
                }
            });
        },

        handleSuccess(data) {
            console.log(data);
            if(this.loading) {
                this.loading.close();
            }
            if(data.success) {
                this.$message.success("上传成功！");
                this.getList();
            } else {
                if(data.data) {
                    let channels = {};
                    this.platforms.forEach(p=>{
                        channels[p.id] = p.platformName;
                    });
                    this.clientPagination.data = (data.data||[]).map(d=>{
                        d.channelStr = channels[d.channel] || '';
                        return d;
                    });
                    this.clientPagination.handleCurrentChange(1);
                    this.errorList = this.clientPagination.subList;
                    this.errorTotal = this.clientPagination.searchParam.total;
                    this.errorPage = 1;
                    this.errorVisible = true;
                } else {
                    this.$message.error(data.msg);
                }
            }
        },
        handleError(arg) {
            console.log(arg);
            if(this.loading) {
                this.loading.close();
            }
            this.$message.error("上传失败");
        },
        //获取平台列表
        getPlatform: function () {
            let vm = this;
            instance({
                method: 'post',
                url: '/v1/author/getPlatFrom'
            }).then(function (data) {
                if (data.data.success) {
                    vm.platforms = data.data.data;
                    vm.getList();
                }
            })
        },
        getAllSku() {
            let self = this;
            instance({
                method: 'post',
                url: 'v1/goods/getList',
                params: {
                    page: 1,
                    rows: 99999,
                    name: '',
                    type: 4
                }
            }).then(function (data) {
                if(data.data.success){
                    let result = (data.data.data.list||[]).map(v=>{ return {value: v.sku};});
                    self.skus = result;
                }
            }).catch(function (err) {

            })
        },
        querySearch(keyword, cb) {
            // /v1/goods/getList?page=1&rows=10&name=03&type=4
            if(this.skus && this.skus.length) {
                let result = this.skus.filter(s=> s.value.indexOf(keyword) > -1);
                cb(result.slice(0, 10));
            } else {
                cb([]);
            }

        },
        beforeUpload() {
            // loading
            this.loading = this.$loading({
                lock: true,
                // text: 'Loading',
                // spinner: 'el-icon-loading',
                background: 'rgba(0, 0, 0, 0.7)'
            });
        },
        handleErrorCurrentChange(page) {
            this.errorPage = page;
            this.clientPagination.handleCurrentChange(page);
            this.errorList = this.clientPagination.subList;
            this.errorTotal = this.clientPagination.searchParam.total;
        },
        handleExport(command) {
            if(command == '1') {
                this.$refs.upload.$refs['upload-inner'].handleClick();
            } else {
                this.handleDownloadTemplate();
            }
        }
      }
  }
</script>
<style>
    .el-upload__input {
        display: none!important;
    }

    .add-dialog .el-form-item__label {
        padding: 0;
    }

    .add-dialog hr {
        margin: 0;
        margin-bottom: 18px;
    }

    .add-dialog .el-dialog__body {
        padding-top: 0;
        padding-bottom: 26px;
    }

    .add-dialog .el-dialog__footer {
        text-align: center;
        padding-top: 0;
    }
</style>
